%% make sure the eye tracker is running before anything else
enableCallbacks = 'PsychEyelinkDispatchCallback';
if Eyelink('Initialize', enableCallbacks) ~= 0
    clc
    disp(' ');
    status = Eyelink('InitializeDummy');
    if Eyelink('InitializeDummy', enableCallbacks) ~=0
        % Failed as well :-(
        Screen('closeall');
        ListenChar(0);
        return;
    end
end
%%
fprintf('\nSTART\n')
clear
c=define_colors(256);
c.BACKGROUND=c.BLACK;
c.GO=c.RED;
c.NG=c.RED;
c.TTEXT=c.WHITE;
edf_name='edf_name';

screenRect=get(0,'ScreenSize');
screenpixW=screenRect(3);
screenpixH=screenRect(4);
c_x=screenpixW/2;
c_y=screenpixH/2;
set(0,'DefaultFigurePosition',[screenpixW*1.25 screenpixH/4   screenpixW/2   screenpixH/2 ])
wherearewe=questdlg_offscreen('Which Computer are you on?', ...
    'Where are you?', ...
    'Prometheus','Sham','Magnet','Sham');
switch wherearewe
    % computer specific information
    case 'Prometheus'
        home_folder='C:\Users\BCoe\DATA\MRI\dorris\inspection';
        distance2screen=66;% cm
        screenwidth=37.7; %-ish  cm
        sheightinches=screenwidth*3/4;
        Screen('Preference', 'SkipSyncTests', 1);
    case 'Sham'
        home_folder='C:\_user\_bcoe\data\dorris\inspection';
        armorbore=questdlg_offscreen('Usingthe ARM mount or in the sham?', ...
            'Where are you?', ...
            'ARM','Bore','ARM');
        switch armorbore
            case 'ARM'
                distance2screen=24;% inches
                screenwidth=340*0.0393700787; % inches
                sheightinches=270*0.0393700787; % inches
                %sheightinches/screenwidth
            case 'Bore'
                distance2screen=23;% inches ???
                screenwidth=17; % inches ???
                sheightinches=screenwidth*3/4;
                disp('dont know these yet');
                return
            otherwise
                disp('cancled by user')
                return
        end
    case 'Magnet'
        home_folder='E:\_User\_bcoe\Data\Dorris\inspection';
        distance2screen=57;% inches
        screenwidth=18; % inches
        sheightinches=screenwidth*3/4;
    otherwise
        disp('cancled by user')
        return
        
end
cd(home_folder)
clear ButtonName screenRect
drawnow;
dphs = atan2(screenwidth/2,distance2screen)*180/pi;%degrees per half screen
ppd = screenpixW/2/dphs; %pixels/degree
uimenufcn(0,'WindowCommandWindow');

%% parameters
%file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
task_num='01';
file_name=['ABC' '.' datestr(now,30) '_' ,task_num ];%datestr(now,'yyyy-mm-dd')
edf_name=[num2str(dayofyear()) 'XXX' task_num];
uimenufcn(0,'WindowCommandWindow');
%% Screen
Screen('Preference','SkipSyncTests',1);
Screen ('Preference','VisualDebugLevel',3);
Screen('Preference','SuppressAllWarnings',1);
% screenNumber=max(Screen('Screens'));
% pixelSize=8;
%[winPtr,windowRect]=Screen('OpenWindow',1,[],[],pixelSize);%for desktop
%w=Screen('OpenWindow',1,[],[],8);%for desktop
ListenChar(0);%turn off character listening and reset the buffer which holds the captured characters.
ListenChar(2);%enable listening, additionally any output of keypresses to Matlab windows is suppressed.
[w, wRect]=Screen('OpenWindow', 1, 0,[],32,2);
Screen(w,'BlendFunction',GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
pause(.01);
Screen('fillrect',w,c.BACKGROUND);
screen('flip',w);

Screen('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
Screen('TextFont',w,'Tahoma');
Screen('TextSize',w,40);
ttext='Hit the space bar to continue';
%tsize=Screen('TextBounds', w, ttext);twidth=tsize(3);
%Screen('DrawText',w,ttext,c_x-(twidth/2),c_y-100,c.TTEXT);
DrawFormattedText(w,ttext,'center','center',c.TTEXT);
screen('flip',w);
fprintf('Hit the space bar to continue\n')
keyCode(32)=0;
while ~keyCode(32)% SPACE on pcwin
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    if keyIsDown
        if keyCode(27) % esc key
            ttext='Task Aborted';
            DrawFormattedText(w,ttext,'center','center',c.ORANGE);
            screen('flip',w);
            fprintf('%s\n',ttext);
            pause(1);
            Screen('Closeall');
            ListenChar(0);
            return
        else
            FlushEvents;
        end
    end
end
screen('flip',w);

%% Eyelink
% done up front
% if Eyelink('Initialize', enableCallbacks) ~= 0
%     clc
%     disp(' ');
%     status = Eyelink('InitializeDummy');
%     if Eyelink('InitializeDummy', enableCallbacks) ~=0
%         % Failed as well :-(
%         Screen('closeall');
%         ListenChar(0);
%         return;
%     end
% end

el = EyelinkInitDefaults_bcoe(w); %el=elglobal; %make it local and usable
%el = EyelinkInitDefaults(w);%el=elglobal; %make it local and usable
%their default is the inverse of this:
el.backgroundcolour = c.BLACK(1);% bcoe
el.foregroundcolour = c.WHITE(1);% bcoe
el.msgfontcolour    = c.M_GREY(1);% bcoe
el.imgtitlecolour   = c.M_GREY(1);% bcoe
el.calibrationtargetcolour=el.foregroundcolour;
EyelinkUpdateDefaults(el); % need to update it on the host

% make sure that we get gaze data from the Eyelink
Eyelink('Command','calibration_type = HV5');
%Eyelink('Command', 'link_sample_data = LEFT,RIGHT,GAZE,AREA');
Eyelink('command', 'link_sample_data  = LEFT,RIGHT,GAZE,PUPIL,AREA,BUTTON,INPUT');
Eyelink('command', 'link_event_filter = LEFT,RIGHT,SACCADE,BLINK,MESSAGE,BUTTON');
Eyelink('command', 'file_event_filter = LEFT,RIGHT,SACCADE,MESSAGE,BUTTON,INPUT');
openfile = Eyelink('openfile',[edf_name,'.edf']);
if openfile~=0
    disp(['Cannot create EDF file: ' edf_name]);
    ttext='Task Aborted';
    DrawFormattedText(w,ttext,'center','center',c.ORANGE);
    screen('flip',w);
    fprintf('%s\n',ttext);
    Eyelink('setofflinemode');
    Eyelink('shutdown');
    pause(1);
    Screen('Closeall');
    ListenChar(0);
    return;
end
%clear openfile
Eyelink('command', 'add_file_preamble_text', 'Recorded by BCOE');

% ttext='Eyelink initialized';
% % tsize=Screen('TextBounds', w, ttext);twidth=tsize(3);
% % Screen('DrawText',w,ttext,c_x-(twidth/2),c_y-100,c.TTEXT);
% DrawFormattedText(w,ttext,'center','center',c.TTEXT);
% screen('flip',w);
% fprintf('%s\n',ttext)

%[v vs]=Eyelink('GetTrackerVersion');
%fprintf('Running experiment on a ''%s'' tracker.\n', vs );

% open file to record data to
%     edfFile='demo.edf';
%     Eyelink('Openfile', edfFile);

% STEP 4
% Calibrate the eye tracker
el;
fprintf(' entered EyelinkDoTrackerSetup\n')
EyelinkDoTrackerSetup(el);
fprintf('  exited EyelinkDoTrackerSetup\n')
FlushEvents;

pause(.5)

%% wait for magnet to start
ttext='waiting for magnet to start';
DrawFormattedText(w,ttext,'center','center',c.TTEXT);
screen('flip',w);
fprintf('%s\n',ttext);

eyelink('command','clear_screen %d',0);
x(1:12)=c_x;
y(1:12)=c_y;
t(1:12)=GetSecs;t=t+(1:length(t));% gets rid of x/0 error
SetMouse(c_x,c_y);
keyIsDown=0;
buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    keyCode=find(keyCode, 1 );
    if keyCode==27% ESC on pcwin
        ttext='Task Aborted';
        DrawFormattedText(w,ttext,'center','center',c.ORANGE);
        screen('flip',w);
        fprintf('%s\n',ttext);
        Eyelink('closefile');
        Eyelink('setofflinemode');
        Eyelink('shutdown');
        pause(1);
        Screen('Closeall');
        ListenChar(0);
        return
    end
    if keyCode==48+5% '5%' on pcwin the new mri trigger
        buttons=1;
    end
    %     temp=simpleserial('bytesready'); % make sure to
    %     if temp > sizeodata*2;
    %         data= simpleserial('read',floor(temp/sizeodata)*sizeodata,'int16');
    %     end
end
%simpleserial('write', char(RecordStart)); % for IScan
%RecordStop=136;  % for IScan
% finally start actual task
%eyelink('StartRecording');
%%
Eyelink('startrecording'); % messages must be AFTER startrecording and require SPRINTF to convert floats to strings
Eyelink('message','RETRACE_INTERVAL: 16.667')
Eyelink('message',sprintf('disttoscreen %1.2f sheightinches %1.2f swidthinches %1.2f PPD %f ',distance2screen,sheightinches,screenwidth,ppd));
%fprintf('disttoscreen %f sheightinches %f swidthinches %f PPD %f ',distance2screen,sheightinches,screenwidth,ppd);
abs_start_time=getsecs;
ttext='start recording';
DrawFormattedText(w,ttext,'center','center',c.GREEN);
screen('flip',w);
fprintf('%s\n',ttext)
pause(1)

for tr = 1:17
    %eyelink('message','TRIAL_START'); %E.messages(starloc),diff(E.mestimes(starloc))
    Eyelink('message', sprintf('TRIAL_START: %d',tr));
    xy=rand(1,2);
    x=round(xy(1)*screenpixW);
    y=round(xy(2)*screenpixH);
    
    eyelink('command','draw_filled_box %d %d %d %d %d',round(x-20),round(y-20),round(x+20),round(y+20),tr-1);
    eyelink('command','draw_text %d %d %d %s ',round(x),round(y),15,sprintf('(%d)',tr-1) );
    Screen('FillOval', w ,c.RED ,[round(x-10),round(y-10),round(x+10),round(y+10)] );
    screen('flip',w);
    eyelink('message',sprintf('FillOval (%d %d %d)',x,y,10)); %E.mestimes(end_loc)
    %eyelink('command','draw_filled_box %d %d %d %d %d',round(windowRect(RectRight)/2-50),round(windowRect(RectBottom)/2-50),(windowRect(RectRight)/2+50),round(windowRect(RectBottom)/2+50),10);
    tic
    while toc<2
        [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
        %warning on MATLAB:DeprecatedLogicalAPI
        if keyIsDown==1
            if lastkeyCode==0
                keyCode=max([0;find(keyCode, 1 )]);
                lastkeyCode=keyCode;
                switch keyCode
                    case 53% INT_5 on pcwin
                        Eyelink('message', sprintf('keyCode: %d: TRtrigger:  %1.02f',keyCode,(getsecs-abs_start_time)*1000));%requires SPRINTF
                        fprintf('keyCode: %d: TRtrigger:  %1.02f\n',keyCode,(getsecs-abs_start_time)*1000);
                    case 49 % keyboard 1! %blue(left) button on right box
                        Eyelink('message', sprintf('keyCode: %d: LEFT:  %1.02f',keyCode,(getsecs-abs_start_time)*1000));%requires SPRINTF
                        fprintf('keyCode: %d: Left:  %1.02f\n',keyCode,(getsecs-abs_start_time)*1000);
                        %case 50 % keyboard 2@
                        %case 51 %keyboard 3#
                    case 52 % keyboard 4$ %red(right) button on right box
                        Eyelink('message', sprintf('keyCode: %d: RIGHT:  %1.02f',keyCode,(getsecs-abs_start_time)*1000));%requires SPRINTF
                        fprintf('keyCode: %d: Right:  %1.02f\n',keyCode,(getsecs-abs_start_time)*1000);
                end
            end %if lastkeyCode==0
        else% if keyIsDown==1
            lastkeyCode=0;% anti hammering
        end
    end
    eyelink('message','TRIAL_END'); %E.mestimes(end_loc)
end
screen('flip',w);
pause(1)

Eyelink('stoprecording');
ttext='stop recording';
DrawFormattedText(w,ttext,'center','center',c.ORANGE);
screen('flip',w);
fprintf('%s\n',ttext)

Eyelink('closefile');
pause(1);
ReceiveFilestatus = Eyelink('ReceiveFile',[edf_name '.edf'],[file_name '.edf']);%, ['dest_is_path']
fprintf(' transferred filesize: %3.0fKB\n', ReceiveFilestatus/2^10)
%%
ListenChar(0);
Screen('closeall');
Eyelink('setofflinemode');
Eyelink('shutdown');
fprintf('END\n')

E=EL1k_step01([pwd filesep file_name '.edf']);
FillOval=E.messages(findincell(E.messages,'FillOval'));
clf;
hold on
for tr=1:length(FillOval)
    fred=textscan(FillOval{tr},'%*s %d %d %d','Delimiter',' ()','MultipleDelimsAsOne',1);
    x=single(fred{1}-(E.res.pix_wide/2))/E.res.ppd;
    y=single(fred{2}-(E.res.pix_wide/2))/E.res.ppd;
    d=single(fred{3})*2/E.res.ppd*100;
    s=plot(x,y,'.','markersize',d,'MarkerFaceColor','auto');
    E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)
    plot(E.eye.x{tr}(E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)),E.eye.y{tr}(E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)),'.g')
end
axis ij